//
//  ZCTakeCarViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/8/15.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCTakeCarViewController.h"
#import "ZCTaskTitleView.h"
#import "ZCTaskListTableViewCell.h"
#import "ZCTaskTotalNumTableViewCell.h"
#import "ZCTaskModel.h"
#import "ZCTakeCarDetailViewController.h"
#import "ZCTakeCarSearchViewController.h"
#import "UWRQViewController.h"


static NSString *taskListCell = @"ZCTaskListTableViewCell";
static NSString *taskTotalNumCell = @"ZCTaskTotalNumTableViewCell";

@interface ZCTakeCarViewController ()<ZCTaskTitleViewDelegate, UITableViewDataSource, UITableViewDelegate, uwRQDelegate>

@property (nonatomic, strong) ZCTaskTitleView *taskTitleView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *taskArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger taskType;
@property (nonatomic, strong) ZCTaskPageInfoModel *pageInfoModel;
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZCTakeCarViewController
#pragma mark - 懒加载
- (NSMutableArray *)taskArray {
    if (!_taskArray) {
        _taskArray = [NSMutableArray array];
    }
    return _taskArray;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, space(80) + 64, SCREENWIDTH, SCREENHEIGHT - space(80) - 64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = ZCColor(0xf7f8fb, 1);
        
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        
        [_tableView registerClass:[ZCTaskListTableViewCell class] forCellReuseIdentifier:taskListCell];
        [_tableView registerClass:[ZCTaskTotalNumTableViewCell class] forCellReuseIdentifier:taskTotalNumCell];
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
    }
    return _tableView;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    self.view.backgroundColor = ZCColor(0xffffff, 1);
    self.navigationItem.title = @"任务列表";
//    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : ZCColor(0xff8213, 1)};
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, space(30), space(30))];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftButtonToBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, space(100), space(100))];
    [rightButton setTitle:@"搜索" forState:UIControlStateNormal];
    [rightButton setTitleColor:ZCColor(0xff8213, 1) forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightButtonToSearch) forControlEvents:UIControlEventTouchUpInside];
    UIButton *scanButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, space(44), space(42))];
    [scanButton setImage:[UIImage imageNamed:@"scanQR"] forState:UIControlStateNormal];
    [scanButton addTarget:self action:@selector(scanButtonToSearch) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    UIBarButtonItem *scanItem = [[UIBarButtonItem alloc] initWithCustomView:scanButton];
    self.navigationItem.rightBarButtonItems = @[searchItem,scanItem];
    self.taskTitleView = [[ZCTaskTitleView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, space(80))];
    self.taskTitleView.delegate = self;
    self.taskTitleView.titleArray = @[@"待寻车", @"待移车", @"待提车"];
    [self.view addSubview:self.taskTitleView];
    
    [self.view addSubview:self.tableView];
    self.taskType = 10;
    self.page = 1;
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [self.hud showAnimated:YES];
    [self loadDataWithTaskType:self.taskType];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 按钮点击
- (void)leftButtonToBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonToSearch {
    ZCTakeCarSearchViewController *searchVC = [[ZCTakeCarSearchViewController alloc] init];
    searchVC.taskType = self.taskType;
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (void)scanButtonToSearch {
    UWRQViewController *rqVC = [[UWRQViewController alloc] init];
    rqVC.delegate = self;
    [self.navigationController pushViewController:rqVC animated:YES];
}

#pragma mark - uwDelegate
- (void)uwRQFinshedScan:(NSString *)result {
    NSArray *res = [result componentsSeparatedByString:@","];
    NSString *vinStr = [res firstObject];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:vinStr forKey:@"queryParam"];
    if (self.taskType > 0) {
        [param setObject:@(self.taskType) forKey:@"taskType"];
    }
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:SearchByQRCode params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                [weakSelf.hud hideAnimated:YES];
                ZCTaskDetailModel *taskDetail = [ZCTaskDetailModel yy_modelWithDictionary:responseObject[@"data"]];
                ZCTakeCarDetailViewController *detailVC = [[ZCTakeCarDetailViewController alloc] init];
                detailVC.taskId = taskDetail.taskId;
                detailVC.taskType = taskDetail.taskType;
                detailVC.fromSearch = YES;
                [weakSelf.navigationController pushViewController:detailVC animated:YES];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - 网络请求
- (void)loadNewData {
    [self loadDataWithTaskType:self.taskType];
}

- (void)loadDataWithTaskType:(NSInteger)type {
    self.page = 1;
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:@(type) forKey:@"taskType"];
        [params setObject:@(self.page) forKey:@"pageNo"];
        [params setObject:@(10) forKey:@"pageSize"];
        NSString *originId = [[NSUserDefaults standardUserDefaults] objectForKey:UserOriginId];
        if (originId.length > 0) {
            [params setObject:originId forKey:@"pointId"];
        }
        
        [ZCHttpTool postWithURL:TaskList params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                [weakSelf.hud hideAnimated:YES];
                [self.taskArray removeAllObjects];
                NSArray *dataArray = responseObject[@"data"];
                for (NSDictionary *dic in dataArray) {
                    ZCTaskModel *taskModel = [ZCTaskModel yy_modelWithDictionary:dic];
                    [self.taskArray addObject:taskModel];
                }
                NSDictionary *pageDic = responseObject[@"pageVo"];
                weakSelf.pageInfoModel = [ZCTaskPageInfoModel yy_modelWithDictionary:pageDic];
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView reloadData];
                if (dataArray.count < 10) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }else {
                    [weakSelf.tableView.mj_footer resetNoMoreData];
                }
                [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:YES];
            }else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.hud showAnimated:YES];
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                });
            }
           
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:YES];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.hud showAnimated:YES];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            });
        }];
    });
    
}

- (void)loadMoreData {
    [self loadMoreDataWithTaskType:self.taskType];
}

- (void)loadMoreDataWithTaskType:(NSInteger)type {
    self.page++;
    __weak typeof(self)weakSelf = self;
    if (self.page <= [self.pageInfoModel.totalPage integerValue]) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:@(type) forKey:@"taskType"];
            [params setObject:@(self.page) forKey:@"pageNo"];
            [params setObject:@(10) forKey:@"pageSize"];
            NSString *originId = [[NSUserDefaults standardUserDefaults] objectForKey:UserOriginId];
            if (originId.length > 0) {
                [params setObject:originId forKey:@"pointId"];
            }
            
            [ZCHttpTool postWithURL:TaskList params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"success"] boolValue]) {
                    NSArray *dataArray = responseObject[@"data"];
                    for (NSDictionary *dic in dataArray) {
                        ZCTaskModel *taskModel = [ZCTaskModel yy_modelWithDictionary:dic];
                        [weakSelf.taskArray addObject:taskModel];
                    }
                    self.pageInfoModel = [ZCTaskPageInfoModel yy_modelWithDictionary:responseObject[@"pageVo"]];
                    [weakSelf.tableView reloadData];
                    if (dataArray.count < 10) {
                        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                    }else {
                        [weakSelf.tableView.mj_footer endRefreshing];
                    }
                }else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.hud showAnimated:YES];
                        weakSelf.hud.mode = MBProgressHUDModeText;
                        weakSelf.hud.label.text = responseObject[@"message"];
                        [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                    });
                }
                
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                self.page--;
                [weakSelf.tableView.mj_footer endRefreshing];
            }];
        });
    }else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    
}

#pragma mark - ZCTaskTitleViewDelegate
- (void)taskTitleViewButttonWithTitle:(NSString *)title {
    if ([title isEqualToString:@"待寻车"]) {
        self.taskType = 10;
    }else if ([title isEqualToString:@"待移车"]) {
        self.taskType = 20;
    }else if ([title isEqualToString:@"待提车"]) {
        self.taskType = 30;
    }
    [self.hud showAnimated:YES];
    [self loadDataWithTaskType:self.taskType];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.taskArray.count + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        ZCTaskTotalNumTableViewCell *numCell = [tableView dequeueReusableCellWithIdentifier:taskTotalNumCell forIndexPath:indexPath];
        numCell.selectionStyle = UITableViewCellSelectionStyleNone;
        numCell.num = [self.pageInfoModel.totalRecord integerValue];
        numCell.line = NO;
        return numCell;
    }else {
    
        ZCTaskListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:taskListCell forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        ZCTaskModel *taskModel = (ZCTaskModel *)self.taskArray[indexPath.section-1];
        cell.taskModel = taskModel;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return space(80);
    }else {
        return space(360);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCTakeCarDetailViewController *detailVC = [[ZCTakeCarDetailViewController alloc] init];
    ZCTaskModel *taskModel = (ZCTaskModel *)self.taskArray[indexPath.section - 1];
    detailVC.taskId = taskModel.taskId;
    detailVC.taskType = taskModel.taskType;
    detailVC.fromSearch = NO;
    [self.navigationController pushViewController:detailVC animated:YES];
}



@end
